<template>
  <a-row justify="space-between">
    <a-col :span="24" style="background-color: #fff; padding: 15px 40px !important; border-radius: 10px;">
      <div class="fish-site-box">
        <div class="site-header">
          <!--    用户信息组件    -->
          <div class="user-info-box">
            <div class="avatar">
              <a-avatar :size="46" :src="fishSiteStore.fishSite.avatar">
              </a-avatar>
            </div>
            <div class="user-info">
              <span class="user-nickname">
                {{ fishSiteStore.fishSite.nickname }} <a-tag color="cyan" style="margin-left: 8px">发布者</a-tag>
              </span>
              <span class="public-time">
                {{ fishSiteStore.fishSite.createTime }}
              </span>
            </div>
          </div>
          <!--  评分数  -->
          <div class="fish-site-rating">
            <div class="rating" v-show="fishSiteStore.fishSite.avgRating && fishSiteStore.fishSite.avgRating !== 0">
              评分：<a-rate :value="fishSiteStore.fishSite.avgRating" allow-half disabled />
            </div>
            <span v-show="!fishSiteStore.fishSite.avgRating && fishSiteStore.fishSite.avgRating === 0"
              class="rating-empty">暂无评分</span>
          </div>
        </div>
        <a-divider style="height: 2px; font-size: 28px; padding-top: 15px;">{{ fishSiteStore.fishSite.name
          }}</a-divider>
        <div class="site-content">
          <!--      <div class="site-name">{{ fishSiteStore.fishSite.name }}</div>-->
          <a-carousel arrows>
            <template #prevArrow>
              <div class="custom-slick-arrow" style="left: 10px; z-index: 1">
                <left-circle-outlined />
              </div>
            </template>
            <template #nextArrow>
              <div class="custom-slick-arrow" style="right: 10px">
                <right-circle-outlined />
              </div>
            </template>
            <img width="100%" height="100%" v-for="item in (fishSiteStore.fishSite.imageUrl || '').split(',')"
              :key="item" :src="item">
          </a-carousel>

          <div class="site-description">{{ fishSiteStore.fishSite.description }}</div>

          <a-divider style="margin-top: 24px;margin-bottom: 10px;" />
          <!--   显示评论条数   -->
          <a-row :align="'middle'" class="site-data">
            <a-tooltip title="收藏">
              <a-button type="text" shape="round" @click="handleCollect">
                <template #icon>
                  <StarOutlined v-show="!fishSiteStore.fishSite.collectFlag" :style="{ fontSize: '16px' }" />
                  <StarFilled v-show="fishSiteStore.fishSite.collectFlag"
                    :style="{ fontSize: '16px', color: '#FADB14' }" />
                </template>
                {{ fishSiteStore.fishSite.collectCount }}
              </a-button>
            </a-tooltip>
          </a-row>
        </div>
      </div>
      <div class="fish-site-comment-box">
        <a-tabs v-model:activeKey="activeKey">
          <a-tab-pane key="comment" tab="评论">
            <!--  评论排序条件   -->
            <a-row :gutter="24" :align="'middle'" :justify="'space-between'" class="comment-header">
              <a-col :span="5"><span class="comment-count">{{
                fishSiteStore.fishSite.ratingCount ? fishSiteStore.fishSite.ratingCount : 0
                  }}个评论</span>
              </a-col>
              <a-col :span="4">
                <a-radio-group v-model:value="pageQuery.orderByColumn" @change="handleOrder" button-style="solid">
                  <a-radio-button value="rating">最高</a-radio-button>
                  <a-radio-button value="create_time">最新</a-radio-button>
                </a-radio-group>
              </a-col>
            </a-row>

            <a-comment>
              <template #avatar>
                <a-avatar size="large" :src="userStore.avatar" :alt="userStore.nickname" />
              </template>
              <template #content>
                <div class="comment-txt-box" style="box-shadow: rgb(238, 238, 238) 0 0 6px;">
                  <a-form-item style="padding: 12px 5px; height: 60px; background-color: #F3F4F6">
                    <a-textarea :bordered="false"
                      style="background-color: #F3F4F6; max-height: 200px; overflow: hidden; " placeholder="大家快来评价~"
                      v-model:value="commentValue" autosize />
                  </a-form-item>

                  <a-form-item name="rate" label="评分" style="margin: 10px 0;">
                    <a-rate v-model:value="rating" />
                  </a-form-item>

                  <div class="comment-txt-footer">
                    <!--      表情列表        -->
                    <a-space :size="8">
                      <V3Emoji @click-emoji="onVue3Emoji">
                        <a-button type="text">
                          <template #icon>
                            <SmileOutlined />
                          </template>
                          表情
                        </a-button>
                      </V3Emoji>
                    </a-space>
                    <a-button html-type="submit" style="border-radius: 20px; width: 80px;" :loading="submitting"
                      type="primary" @click="handleSubmit">
                      发布
                    </a-button>
                  </div>
                </div>
              </template>
            </a-comment>

            <!-- 评论列表显示：没有二级评论  -->
            <a-list class="comment-list" :loading="initLoading" item-layout="horizontal"
              :data-source="fishSiteCommentList" v-show="fishSiteCommentList.length > 0">
              <template #loadMore>
                <div v-if="!initLoading && !loading && fishSiteCommentList.length < total"
                  :style="{ textAlign: 'center', marginTop: '12px', height: '32px', lineHeight: '32px' }">
                  <a-button @click="onLoadingMore">加载更多</a-button>
                </div>
                <a-divider v-else style="margin-top: 45px;">已经到底了 🤐</a-divider>
              </template>
              <template #renderItem="{ item }">
                <a-list-item>
                  <a-comment :author="item.username" :avatar="item.avatar">
                    <template #content>
                      <div style="display: flex;justify-content: space-between">
                        <p>
                          {{ item.comment }}
                        </p>
                        <div class="rating">
                          <a-rate :value="item.rating" disabled />
                        </div>
                      </div>

                    </template>
                    <template #datetime>
                      <a-tooltip :title="item.createTime">
                        <span>{{ item.createTime }}</span>
                      </a-tooltip>
                      <a-tag v-if="item.userId === fishSiteStore.fishSite.userId" color="cyan"
                        style="margin-left: 8px">发布者</a-tag>
                    </template>
                  </a-comment>
                </a-list-item>
              </template>
            </a-list>
            <a-empty v-show="fishSiteCommentList.length <= 0">
              <template #description>
                <span>
                  暂无内容
                </span>
              </template>
            </a-empty>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-col>

  </a-row>

</template>

<script setup lang="ts">
import {
  LeftCircleOutlined,
  RightCircleOutlined,
  SmileOutlined,
  EditOutlined,
  StarFilled,
  StarOutlined
} from '@ant-design/icons-vue';
import { message as AntdMessage } from 'ant-design-vue';
import { onMounted } from "vue";
import { useRoute } from "vue-router";
import { getPublicDetail } from "@/api/front/angling";
import useFishSiteStore from "@/store/modules/fistSite";
import useUserStore from "@/store/modules/user";
import { anglingCommentGet, anglingCommentPush } from "@/api/front/angling";
import { CommentFishSiteVo } from "@/api/front/comment/types";
import V3Emoji from "vue3-emoji";
import "vue3-emoji/dist/style.css";
import { collectFishSite } from "@/api/front/collect";


const pageQuery = reactive({
  pageSize: 3,
  pageNum: 1,
  orderByColumn: 'rating',
  isAsc: 'desc',
  fishSiteId: undefined
})

const route = useRoute()
const fishSiteStore = useFishSiteStore()
const userStore = useUserStore();
const activeKey = ref('comment')

// 初始化数据loading
const initLoading = ref(true);
// 加载跟多的按钮loading
const loading = ref(false);
// 评论值
const commentValue = ref('')
// 发布按钮loading
const submitting = ref(false)
const total = ref()
const rating = ref(0)
/**
 * 监听评论发布按钮
 */
const handleSubmit = async () => {
  // 检查用户是否登录
  const isLoggedIn = await userStore.isLoggedIn()
  if (!isLoggedIn) {
    AntdMessage.warning('请先登录');
    return;
  }

  // 校验 commentValue 是否为空字符串
  if (!commentValue.value || commentValue.value.trim() === '') {
    AntdMessage.warning('评论内容不能为空');
    return;
  }

  submitting.value = true;
  try {
    const formData = {
      fishSiteId: parseInt(route.params.fishSiteId as string),
      comment: commentValue.value,
      rating: rating.value
    };
    await anglingCommentPush(formData);
    // 刷新评论列表
    await getCommentList();
    rating.value = 0;
    commentValue.value = '';
    AntdMessage.success('发布成功');
  } finally {
    submitting.value = false;
  }
}
/**
 * 监听收藏按钮
 */
const handleCollect = async () => {
  try {
    await collectFishSite({
      type: fishSiteStore.fishSite.collectFlag ? 'uncollect' : 'collect',
      fishSiteId: fishSiteStore.fishSite.fishSiteId,
      authorId: fishSiteStore.fishSite.userId
    })

    // 更新本地收藏状态和收藏数量
    const newCollectFlag = !fishSiteStore.fishSite.collectFlag;
    const newCollectCount = newCollectFlag
      ? fishSiteStore.fishSite.collectCount + 1
      : fishSiteStore.fishSite.collectCount - 1;

    // 更新store中的fishSite信息
    await fishSiteStore.setFishSite({
      ...fishSiteStore.fishSite,
      collectFlag: newCollectFlag,
      collectCount: newCollectCount
    });
    AntdMessage.success('操作成功');
  } finally {
    // 刷新页面
  }
}

// 评论列表
let fishSiteCommentList = reactive<Array<CommentFishSiteVo>>([])
/**
 * 监听获取更多 1 评论按钮
 */
const onLoadingMore = async () => {
  // 检查是否还有更多评论可以加载
  if (total.value && pageQuery.pageSize * pageQuery.pageNum >= total.value) {
    AntdMessage.info('没有更多评论了');
    return;
  }

  pageQuery.pageNum++;
  try {
    loading.value = true;

    // 设置查询参数
    pageQuery.fishSiteId = fishSiteStore.fishSite.fishSiteId;

    // 获取更多评论
    const listRes = await anglingCommentGet(pageQuery);

    // 确保我们有新的评论数据，并且是数组形式
    if (Array.isArray(listRes.data.rows)) {
      // 使用展开运算符将新数据合并到现有数组中
      fishSiteCommentList.push(...listRes.data.rows);
    }
  } catch (error) {
    console.error('Failed to load more comments:', error);
    AntdMessage.error('加载更多评论失败，请重试');
  } finally {
    loading.value = false;

    // 确保 DOM 已经更新
    await nextTick(() => {
      window.dispatchEvent(new Event('resize'));
    });
  }
}
const handleOrder = async () => {
  // pageQuery重新赋值
  pageQuery.pageSize = 10
  pageQuery.pageNum = 1
  await getCommentList()
}
const getCommentList = async () => {
  pageQuery.fishSiteId = parseInt(route.params.fishSiteId as string)
  const listRes = await anglingCommentGet(pageQuery);
  fishSiteCommentList.splice(0, fishSiteCommentList.length, ...listRes.data.rows);
  total.value = listRes.data.total
  initLoading.value = false;

}


/*
Emoji表情
 */
const onVue3Emoji = (val) => {
  commentValue.value += val;
};

/**
 * 初始化数据
 */
const initData = async () => {
  const fishSiteIdStr = route.params.fishSiteId as string;
  const fishSiteId = parseInt(fishSiteIdStr, 10);

  if (isNaN(fishSiteId) || fishSiteId <= 0) {
    AntdMessage.error('无效的鱼场ID');
    return;
  }

  try {
    const detailRes = await getPublicDetail(fishSiteId);
    const fishSiteData = detailRes.data;
    fishSiteData.avgRating = parseFloat(String(fishSiteData.avgRating));
    // 确保 imageUrl 字段存在且是字符串
    if (!fishSiteData.imageUrl || typeof fishSiteData.imageUrl !== 'string') {
      fishSiteData.imageUrl = ''; // 或者使用默认图片 URL
    }

    await getCommentList();
    await fishSiteStore.setFishSite(fishSiteData);
  } catch (error) {
    console.error('Failed to initialize data:', error);
    AntdMessage.error('初始化数据失败，请重试');
  } finally {
    initLoading.value = false;
  }
}

onMounted(async () => {
  await initData();
});
</script>

<style scoped lang="scss">
:deep(.tippy-content) {
  padding: 0px;
  width: 0px;
}  
.site-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .user-info-box {
    display: flex;
    align-content: center;
    align-items: center;

    .user-info {
      display: flex;
      justify-content: space-around;
      align-content: space-around;
      flex-direction: column;
      margin-left: 10px;
      height: 46px;

      .user-nickname {
        color: #262626;
        font-weight: bolder;
      }

      .public-time {
        color: #9CA3AF;
      }
    }
  }

  .fish-site-rating {
    .rating {
      display: flex;
      align-items: center;
      font-size: 24px;

      span {
        margin-right: 5px;
      }
    }

    .rating-empty {
      color: #9CA3AF;
    }
  }
}

.site-content {
  margin-top: 40px;

  .site-data {
    padding-top: 10px;
    padding-bottom: 15px;
    font-size: 58px;
  }
}

.comment-txt-box {
  padding: 15px;
  background-color: white;
  border-radius: .5rem;

  .comment-txt-footer {
    display: flex;
    justify-content: space-between;
    align-content: center;
    align-items: center;
  }
}

.comment-list {
  .rating {
    display: flex;
    align-items: center;

    span {
      margin-right: 5px;
    }
  }
}
</style>

<style scoped>
:deep(.slick-slide) {
  text-align: center;
  height: 380px;
  overflow: hidden;
}

:deep(.slick-slide img) {
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* 保持图片的比例且填充整个轮播图 */
}

:deep(.slick-arrow.custom-slick-arrow) {
  width: 25px;
  height: 25px;
  font-size: 25px;
  color: #fff;
  background-color: rgba(31, 45, 61, 0.21);
  transition: ease all 0.3s;
  opacity: 0.2;
  z-index: 1;
}

:deep(.slick-arrow.custom-slick-arrow:before) {
  display: none;
}

:deep(.slick-arrow.custom-slick-arrow:hover) {
  color: #fff;
  opacity: 0.5;
}

:deep(.ant-comment-content-author-name) {
  color: #262626 !important;
  font-size: 16px !important;
  font-weight: bolder !important;
}

:deep(.ant-comment-avatar>img) {
  width: 40px;
  height: 40px;
}

:deep(.ant-comment .ant-comment-avatar img) {
  width: 40px;
  height: 40px;
}

:deep(.ant-comment) {
  width: 100%;
}

:deep(.ant-form-item) {
  margin-bottom: 0;
}
</style>